package vn.ugame.demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import vn.ugame.security.client.Config;
import vn.ugame.security.client.Security;
import vn.ugame.service.client.ActivateService;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final EditText txtCode = (EditText) findViewById(R.id.txtCode);
		final Button btnSend = (Button) findViewById(R.id.btnSend);

		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		String imei = telephonyManager.getDeviceId();

		String settings = null;
		try {
			settings = ReadSettings();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			Toast.makeText(this, e1.getMessage(), Toast.LENGTH_LONG).show();
		}

		if (settings == null) {
			try {
				String responseValue = "";
				ActivateService activeService = new ActivateService();
				responseValue = activeService.checkActivated(imei);

				if (responseValue != "") {
					String secretImei = Security.getInstance().getMD5(imei);
					responseValue = Security.getInstance().encrypt(
							responseValue, secretImei);
					WriteSettings(responseValue);
					Toast.makeText(MainActivity.this, "Data saved",
							Toast.LENGTH_LONG).show();
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				Toast.makeText(this, e1.getMessage(), Toast.LENGTH_LONG).show();
			}
		} else {
			try {
				String secretImei = Security.getInstance().getMD5(imei);
				settings = Security.getInstance().decrypt(settings, secretImei);
				String msg = "";
				if (isActivated(settings)) {
					msg = "Application has been activated";
				} else {
					msg = "Not activated";
				}
				Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				Toast.makeText(this, e1.getMessage(), Toast.LENGTH_LONG).show();
			}
		}

		btnSend.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				String code = txtCode.getText().toString();

				TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
				String imei = telephonyManager.getDeviceId();

				String responseValue = "";
				ActivateService activeService = new ActivateService();
				try {
					responseValue = activeService.activateApp(code, imei);
				} catch (Exception e) {
					// TODO Auto-generated catch block
				}

				if (responseValue != "") {
					try {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								MainActivity.this);
						builder.setTitle("Nofication");
						builder.setPositiveButton("Continue",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

									}
								});
						if (isActivated(responseValue)) {
							builder.setMessage("Activate successfull");
						} else {
							builder.setMessage("Activate failed");
						}
						builder.show();

						String secretImei = Security.getInstance().getMD5(imei);
						responseValue = Security.getInstance().encrypt(
								responseValue, secretImei);
						WriteSettings(responseValue);
						Toast.makeText(MainActivity.this, "Data saved",
								Toast.LENGTH_LONG).show();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						Toast.makeText(MainActivity.this, e.getMessage(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	// Save settings

	public void WriteSettings(String data) throws Exception {
		FileOutputStream fOut = null;
		OutputStreamWriter osw = null;
		try {
			fOut = openFileOutput("config.dat", MODE_PRIVATE);
			osw = new OutputStreamWriter(fOut);
			osw.write(data);
			osw.flush();
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				osw.close();
				fOut.close();
			} catch (IOException e) {
				throw e;
			} catch (Exception e) {
				throw e;
			}
		}
	}

	// Read settings

	public String ReadSettings() throws Exception {
		FileInputStream fIn = null;
		InputStreamReader isr = null;
		char[] inputBuffer = new char[255];
		String data = null;
		try {
			fIn = openFileInput("config.dat");
			isr = new InputStreamReader(fIn);
			isr.read(inputBuffer);
			data = new String(inputBuffer);
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				isr.close();
				fIn.close();
			} catch (IOException e) {
				throw e;
			} catch (Exception e) {
				throw e;
			}
		}
		return data;
	}

	private boolean isActivated(String data) throws Exception {
		try {
			String status = data.split(Config.ACTIVATE_DELIMITER)[0];
			if (status.equals(Config.ACTIVATE_FAILED)) {
				return false;
			} else if (status.equals(Config.ACTIVATE_SUCCESS)) {
				return true;
			}
			return false;
		} catch (Exception ex) {
			throw ex;
		}
	}
}
